import { ValidationError } from 'class-validator';

// 中文验证错误消息映射
export const zhCNValidationMessages = {
  required: '${property}是必填项',
  isNotEmpty: '${property}不能为空',
  isString: '${property}必须是字符串类型',
  isNumber: '${property}必须是数字类型',
  isInt: '${property}必须是整数',
  isBoolean: '${property}必须是布尔值',
  isDate: '${property}必须是日期格式',
  isEmail: '${property}格式不正确，请输入有效的邮箱地址',
  isMobilePhone: '${property}格式不正确，请输入有效的手机号码',
  minLength: '${property}长度不能少于${constraints[0]}个字符',
  maxLength: '${property}长度不能超过${constraints[0]}个字符',
  min: '${property}不能小于${constraints[0]}',
  max: '${property}不能大于${constraints[0]}',
  matches: '${property}格式不正确',
  isArray: '${property}必须是数组类型',
  unique: '${property}已存在，请更换',
  isPositive: '${property}必须是正数',
  isUrl: '${property}必须是有效的URL地址',
};

// 自定义验证错误格式化函数
export function formatValidationError(error: ValidationError): string {
  // 处理嵌套错误
  if (error.children && error.children.length > 0) {
    const childErrors = error.children
      .map((childError) => formatValidationError(childError))
      .filter(Boolean);
    if (childErrors.length > 0) {
      return childErrors.join('; ');
    }
  }

  // 处理当前错误
  if (error.constraints) {
    const constraintMessages = Object.entries(error.constraints).map(
      ([type, message]) => {
        // 替换默认消息为中文消息
        const propertyName = error.property;
        if (zhCNValidationMessages[type]) {
          let chineseMessage = zhCNValidationMessages[type];
          // 替换${property}占位符
          chineseMessage = chineseMessage.replace(
            /\${property}/g,
            propertyName,
          );
          // 替换${constraints[0]}等占位符
          if (error.constraints?.[type]?.includes('$constraint')) {
            const regex = /\${constraints\[(\d+)\]}/g;
            chineseMessage = chineseMessage.replace(regex, (_, index) => {
              return (
                error.constraints?.[type]?.match(/\d+/g)?.[parseInt(index)] ||
                ''
              );
            });
          }
          return chineseMessage;
        }
        // 如果没有对应的中文消息，直接返回原始消息
        return message;
      },
    );
    return constraintMessages.join('; ');
  }

  return '';
}
